package vn.vfriends.games.bean;

import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.games.jpa.entity.News;
import vn.vfriends.games.service.NewsService;
import vn.vfriends.id.ws.User;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@ConversationScoped
public class NewsBean implements Serializable {
    private final Logger logger = LoggerFactory.getLogger(NewsBean.class);
    
    @Inject private NewsService newsService;
    @Inject private Conversation conversation;
    private News[] selectedNews;
    private News news;
    private List<News> newsList;
    
    private long newsId;
    
    @PostConstruct
    public void init(){
        newsList = newsService.findNews();
    }

    public long getNewsId() {
        return newsId;
    }

    public void setNewsId(long newsId) {
        this.newsId = newsId;
    }

    public List<News> getNewsList() {
        return newsList;
    }

    public List<News> getDisplayNewsList() {
        return newsService.findDisplayNews();
    }
    
    public News[] getSelectedNews() {
        return selectedNews;
    }

    public void setSelectedNews(News[] selectedNews) {
        this.selectedNews = selectedNews;
    }

    public News getNews() {
        return news;
    }

    public void setNews(News news) {
        this.news = news;
    }

    public Conversation getConversation() {
        return conversation;
    }
    
    public void preRenderNewsDetailAction() {
        if(newsId > 0) {
            news = this.newsService.findNews(newsId);
        }
    }
    
    public void preNewAction() {
        news = new News();
        
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }
    
    public String preViewAction() {
        String outcome = "";
        FacesContext context = FacesContext.getCurrentInstance();
        
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.news != null) {
                outcome = "view?faces-redirect=true";
            }
            else if (this.selectedNews == null || this.selectedNews.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một tin tức/sự kiện", ""));
            } else if (this.selectedNews.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một tin tức/sự kiện", ""));
            } else {
                this.news = this.selectedNews[0];
                outcome = "view?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
        return outcome;
    }
    
    public String preEditAction() {
        String outcome = null;
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.news != null){
                outcome = "edit?faces-redirect=true";
            } else if (this.selectedNews == null || this.selectedNews.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một tin tức/sự kiện", ""));
            } else if (this.selectedNews.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một tin tức/sự kiện", ""));
            } else {
                this.news = this.selectedNews[0];
                outcome = "edit?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));

        }
        return outcome;
    }
    
    public void preDeleteAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            if ((this.news == null) && (this.selectedNews == null || this.selectedNews.length == 0)) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn tin tức/sự kiện", ""));
            }
        } catch (Exception e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
    
    public String saveAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            HttpSession session = request.getSession();
            User loggedUser = (User)session.getAttribute("LOGGED_USER");
            news.setPublisher(loggedUser.getEmail());
            this.newsService.create(news);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }
    
    public String updateAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            HttpSession session = request.getSession();
            User loggedUser = (User)session.getAttribute("LOGGED_USER");
            news.setPublisher(loggedUser.getEmail());
            this.newsService.edit(news);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }

    public String cancelAction() {
        conversation.end();
        return "list?faces-redirect=true";
    }
    
    public void deleteAction() {
        try {
            if(this.news != null) {
                this.newsService.destroy(this.news.getId());
            }
            else {
                for(News sNews : selectedNews) {
                    this.newsService.destroy(sNews.getId());
                }
            }
            if(!conversation.isTransient()) {
                conversation.end();
            }
            FacesContext.getCurrentInstance().getExternalContext().redirect("list.jsf");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
}
